// app.js 整合优化版
let chart24h, chart7d;

// 初始化图表
function initCharts() {
    chart24h = echarts.init(document.getElementById('chart24h'));
    chart7d = echarts.init(document.getElementById('chart7d'));
}

// 统一图表配置
const baseChartOption = {
    tooltip: { trigger: 'axis' },
    legend: { data: ['温度', '湿度'] },
    xAxis: {
        type: 'category',
        boundaryGap: false,
        axisLabel: {
            interval: 0, // 强制显示所有标签
            formatter: function (value) {
                return value + '时'; // 显示为"10时"格式
            }
        },
        splitLine: { show: true }
    },
    yAxis: [
        {
            type: 'value',
            name: '温度(℃)',
            min: function(value) { return Math.floor(value.min) - 1; },
            max: function(value) { return Math.ceil(value.max) + 1; }
        },
        {
            type: 'value',
            name: '湿度(%)',
            min: 0,
            max: 100
        }
    ],
    series: [
        {
            name: '温度',
            type: 'line',
            yAxisIndex: 0,
            connectNulls: true,
            symbol: 'emptyCircle',
            symbolSize: 8,
            itemStyle: { color: '#e74c3c' },
            data: [] // 初始化空数据
        },
        {
            name: '湿度',
            type: 'line',
            yAxisIndex: 1,
            connectNulls: true,
            symbol: 'emptyCircle',
            symbolSize: 8,
            itemStyle: { color: '#3498db' },
            data: []
        }
    ],
    dataZoom: [{
        type: 'slider',
        show: true,
        start: 0,
        end: 100,
        height: 20,
        bottom: 10
    }]
};

// 通用数据获取
async function fetchData(url) {
    try {
        const res = await fetch(url);
        if (!res.ok) throw new Error(`请求失败: ${res.status}`);
        return await res.json();
    } catch (err) {
        console.error(`请求异常(${url}):`, err);
        showError(err.message);
        return null;
    }
}

// 主数据加载
async function loadData() {
    const limit = document.getElementById('rowLimit').value;
    const loading = document.getElementById('loading');
    const error = document.getElementById('error');

    loading.style.display = 'block';
    error.style.display = 'none';

    try {
        const [historyData, latestData] = await Promise.all([
            fetchData(`/api/history?limit=${limit}`),
            fetchData('/api/latest')
        ]);

        if (historyData) updateHistoryTable(historyData);
        if (latestData) updateRealtime(latestData);

    } finally {
        loading.style.display = 'none';
    }
}

// 加载统计图表
async function loadAllStats() {
    const [data24h, data7d] = await Promise.all([
        fetchData('/api/stats/24h_trend'),
        fetchData('/api/stats/7d_trend')
    ]);

    if (data24h) update24hChart(data24h);
    if (data7d) updateChart(chart7d, data7d, 'date');
}

// 加载小时统计
async function loadHourlyStats() {
    try {
        const [hourlyData] = await Promise.all([
            fetchData('/api/stats/hourly'),
            loadAllStats() // 同步刷新图表
        ]);

        if (!hourlyData) return;

        document.getElementById('hourlyStats').innerHTML = hourlyData.map(item => `
            <div class="stat-item">
                <span>${item.hour}</span>
                <span class="temp">${item.avg_temperature?.toFixed(1) ?? '--'}℃</span>
                <span class="hum">${item.avg_humidity?.toFixed(1) ?? '--'}%</span>
            </div>
        `).join('');
    } catch (err) {
        console.error('小时统计加载失败:', err);
    }
}

// 修改图表更新逻辑
function updateChart(chart, data, xKey) {
    const validData = data.filter(d => d.temperature !== null && d.humidity !== null);

    chart.setOption({
        xAxis: {
            data: data.map(d => d[xKey])
        },
        series: [
            { data: data.map(d => d.temperature) },
            { data: data.map(d => d.humidity) }
        ]
    }, true);
}

// 更新24小时图表函数
function update24hChart(data) {
    const xData = data.map(d => d.hour);
    const tempData = data.map(d => d.temperature);
    const humData = data.map(d => d.humidity);

    chart24h.setOption({
        xAxis: {
            data: xData,
            axisLabel: {
                formatter: function(value) {
                    return value; // 直接显示后端返回的小时数值
                }
            }
        },
        series: [
            { data: tempData },
            { data: humData }
        ]
    }, true);
}

// 更新实时数据
function updateRealtime(data) {
    const tempElem = document.getElementById('currentTemp');
    const humElem = document.getElementById('currentHum');
    const timeElem = document.getElementById('updateTime');

    if (!data || data.error) {
        tempElem.textContent = '--';
        humElem.textContent = '--';
        timeElem.textContent = '更新失败';
        return;
    }

    tempElem.textContent = data.temperature?.toFixed(1) ?? '--';
    humElem.textContent = data.humidity?.toFixed(1) ?? '--';
    timeElem.textContent = data.timestamp || '刚刚';
}

// 更新历史表格
function updateHistoryTable(data) {
    const tbody = document.getElementById('dataBody');
    tbody.innerHTML = data.map(item => `
        <tr>
            <td>${item.timestamp}</td>
            <td>${item.temperature?.toFixed(1) ?? '--'}</td>
            <td>${item.humidity?.toFixed(1) ?? '--'}</td>
        </tr>
    `).join('');
}

// 显示错误
function showError(message) {
    const errorElem = document.getElementById('error');
    errorElem.textContent = `错误: ${message}`;
    errorElem.style.display = 'block';
}

// 初始化
window.onload = () => {
    initCharts();
    loadData();
    loadHourlyStats();
};